import { login, getInfo } from "@/api/user"
import { resetRouter } from "@/router"

const getDefaultState = () => {
    return {
        user: null // 储存登录后用户信息
    }
}

const state = getDefaultState()

const mutations = {
    SET_USER(state, payload) {
        state.user = payload
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { loginId, loginPwd, captcha, checked, callback } = userInfo
        return new Promise((resolve, reject) => {
            login({ loginId: loginId.trim(), loginPwd: loginPwd, captcha: captcha, remember: checked ? 7 : false })
                .then((response) => {
                    const { data } = response
                    if (data) {
                        commit("SET_USER", data)
                        // 如果有数据，则用户名密码匹配到了
                        callback()
                        resolve()
                    } else {
                        // data没数据表示：用户名和密码错误，但是验证码正确
                        callback()
                        reject(response)
                    }
                })
                .catch((error) => {
                    callback()
                    reject(error)
                })
        })
    },
    getInfo({ commit }) {
        return new Promise((resolve, reject) => {
            getInfo()
                .then((res) => {
                    if (typeof res === "string") {
                        // 说明未登录或token过期
                        res = JSON.parse(res)
                        if (res.code === 401) {
                            reject(res.msg)
                        }
                    } else {
                        // 说明token有效，将用户信息放入仓库
                        commit("SET_USER", res.data)
                        resolve()
                    }
                })
                .catch((error) => {
                    reject(error)
                })
        })
    },
    // 退出登录
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            localStorage.removeItem("token")
            commit("SET_USER", null)
            resetRouter()
            resolve()
        })
    },

    // 去掉token
    resetToken({ commit }) {
        return new Promise((resolve) => {
            localStorage.removeItem("token")
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
